//  Inside Microsoft Exchange 2007 Web Services 
//  Chapter 9
//
//  Copyright (c) 2007 David Sterling, Ben Spain, Mark Taylor, Huw Upshall, Michael Mainer.  
//  All rights reserved.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using ProxyHelpers.EWS;

namespace GetRecurringMasterFromOccurrenceId
{
    class Program
    {
        static void Main(string[] args)
        {
            ExchangeServiceBinding binding = new ExchangeServiceBinding();
            binding.Url = @"https://yourServer/ews/Exchange.asmx";
            binding.Credentials = new NetworkCredential(
                "username",
                "password",
                "domain");

            // You must first have the ItemId of an occurrence before calling 
            // GetRecurringMasterFromOccurrenceId
            //
        }

        /// <summary>
        /// Get a recurring master for a recurring series from the id
        /// of one of the occurrences. (Listing 9-5)
        /// </summary>
        /// <param name="binding">Binding to use for the web service call</param>
        /// <param name="idOfOccurrence">id of an occurence within the series</param>
        /// <returns>Id of the recurring master for the series</returns>
        ///
        public static ItemIdType GetRecurringMasterFromOccurrenceId(
            ExchangeServiceBinding binding,
            ItemIdType idOfOccurrence)
        {
            // Create the RecurringMasterItemIdType instance that we will pass to GetItem.
            //
            RecurringMasterItemIdType recurringMasterId =
                new RecurringMasterItemIdType();
            recurringMasterId.OccurrenceId = idOfOccurrence.Id;
            recurringMasterId.ChangeKey = idOfOccurrence.ChangeKey;

            GetItemType getItemRequest = new GetItemType();
            getItemRequest.ItemShape = new ItemResponseShapeType();
            getItemRequest.ItemShape.BaseShape = DefaultShapeNamesType.IdOnly;

            getItemRequest.ItemIds = new RecurringMasterItemIdType[] { recurringMasterId };

            // Make the call to the GetItem web method, check for success
            // and return the item id accordingly
            //
            GetItemResponseType response = binding.GetItem(getItemRequest);
            ItemInfoResponseMessageType responseMessage =
                response.ResponseMessages.Items[0] as ItemInfoResponseMessageType;

            if (responseMessage.ResponseCode != ResponseCodeType.NoError)
            {
                throw new Exception("GetItem failed with response code " +
                         responseMessage.ResponseCode.ToString());
            }

            return responseMessage.Items.Items[0].ItemId;
        }
    }
}
